﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.MahasiswaView
{
    public partial class QuizMhsPage : PhoneApplicationPage
    {
        private Perkuliahan kuliah;
        private Quiz selectedQuiz;
        private DateTime serverTime;

        public QuizMhsPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if(e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                LoadQuizList();
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.KULIAH))
            {
                kuliah = (Perkuliahan)PhoneApplicationService.Current.State[Config.KULIAH];
            }
            if (kuliah == null)
            {
                kuliah = new Perkuliahan();
                kuliah.Mhs = (Mahasiswa)SavedUser.Instance.User.ConvertUser();
            }

            GetServerTime();
            LoadQuizList();
        }

        private void GetServerTime()
        {
            string url = string.Format("{0}&{1}", Config.Instance.COMMON_SERVICE_URL() + "?action=time", Guid.NewGuid().ToString());

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getTime_DownloadStringCompleted);
            try
            {
                webClient.DownloadStringAsync(uri);
            }
            catch (Exception)
            {
                serverTime = DateTime.Now;
            }
        }

        private void getTime_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string result = e.Result;
                serverTime = DateTime.Parse(result);
            }
            catch (Exception ex)
            {
                serverTime = DateTime.Now;
            }
        }

        private void LoadQuizList()
        {
            listQuiz.ItemsSource = null;
            selectedQuiz = null;

            string url = string.Format("{0}&{1}", Config.Instance.QUIZ_SERVICE_URL() + Config.VIEW_ACTION_KEY + "QuizMhs", Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(kuliah);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listQuiz_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listQuiz_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                QuizList list = JsonConvert.DeserializeObject<QuizList>(e.Result);
                if (list.Count > 0)
                    listQuiz.ItemsSource = list;
                else
                    listQuiz.ItemsSource = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            pivotQuiz.SelectedIndex = 0;
        }

        private void listQuiz_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            try
            {
                if (e.AddedItems.Count > 0)
                {

                    selectedQuiz = (Quiz)e.AddedItems[0];
                    ((ListBox)sender).SelectedIndex = -1;

                    if (selectedQuiz != null)
                    {
                        pivotQuiz.SelectedIndex = 1;
                        textBoxQuis.Text = selectedQuiz.Nama;
                        textBoxMatkul.Text = selectedQuiz.DetMatkul.Matkul.Nama;
                        textBoxCreated.Text = selectedQuiz.Awal.ToString("D");
                        textBoxBatas.Text = selectedQuiz.Akhir.ToString("D");
                        textBoxJam.Text = selectedQuiz.Mulai.Value.ToString("t") + " - " + selectedQuiz.Selesai.Value.ToString("t");
                        bool isReady = selectedQuiz.Mulai <= serverTime && selectedQuiz.Selesai >= serverTime;
                        int divTime = (int)selectedQuiz.Selesai.Value.Subtract(serverTime).TotalMinutes;
                        string sisaWaktu = isReady && divTime > 0 ? (" / sisa " + divTime + " menit") : "";
                        sisaWaktu = serverTime < selectedQuiz.Mulai ? " / Sudah lewat" : serverTime > selectedQuiz.Selesai ? " / Belum dimulai" : sisaWaktu;
                        textBoxWaktu.Text = Convert.ToString(selectedQuiz.Waktu) + " menit" + sisaWaktu;
                        textBoxJumlahSoal.Text = Convert.ToString(selectedQuiz.Jumlah) + " soal";
                        textBoxStatus.Text = selectedQuiz.Status == true ? "Sudah dikerjakan" : "Belum Mengerjakan";
                        buttonKerjakan.IsEnabled = !selectedQuiz.Status && isReady && divTime > 0;
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            GetServerTime();
            LoadQuizList();
        }

        private void undoButton_Click(object sender, EventArgs e)
        {
            if (pivotQuiz.SelectedIndex > 0)
                pivotQuiz.SelectedIndex = 0;
            else
                NavigationService.GoBack();
        }

        private void buttonKerjakan_Click(object sender, RoutedEventArgs e)
        {

            if (MessageBox.Show("Kerjakan quis sekarang?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                Utility.GotoPage(this, "/View/Mahasiswa/QuestionPage.xaml");
                PhoneApplicationService.Current.State[Config.QUIZ] = selectedQuiz;
            }
        }
    }
}